package com.feinno.urcs.group.interop.task;

import com.feinno.rpc.channel.RpcFuture;
import com.feinno.rpc.client.RpcMethodStub;
import com.feinno.urcs.group.api.FXLogicPoolService;
import com.feinno.urcs.group.api.FXUserIndexService;
import com.feinno.urcs.group.interop.entity.FXCatalogIndex;
import com.feinno.urcs.group.interop.entity.FetionInviteArgs;
import com.feinno.urcs.group.interop.entity.OperateType;
import com.feinno.urcs.group.siptask.task.GroupTaskEvents;
import org.helium.framework.annotations.FieldSetter;
import org.helium.framework.annotations.ServiceSetter;
import org.helium.framework.annotations.TaskImplementation;
import org.helium.framework.rpc.LegacyRpcClient;
import org.helium.framework.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 需要通过 entity 中 OperateType {@link OperateType} 判定具体业务
 *
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
@TaskImplementation(event = GroupTaskEvents.GROUP_FETION_INVITE_MEMBER)
public class FXInviteMemberTask implements Task<FetionInviteArgs> {
	private static final Logger LOGGER = LoggerFactory.getLogger(FXInviteMemberTask.class);
	private String rpcMethodNameInvite = "InviteMember";
	private String rpcMethodNameAccept = "JoinGroup";

	@FieldSetter("${FX_GROUP_SERVICE_XML}")
	private LegacyRpcClient rpcClient;
	@ServiceSetter
	private FXLogicPoolService groupLogicPool;
	@ServiceSetter
	private FXUserIndexService fxUserIndexService;

	@Override
	public void processTask(FetionInviteArgs args) {
		try {
//			int groupPoolId = groupLogicPool.getLogicPool(args.getGroup().getGroupId());
			FXCatalogIndex fxOperaIndex = fxUserIndexService.getFXCatalogIndex(args.getGroup().getOperatorMobileNo());
			args.getGroup().setOperatorUid(fxOperaIndex.getUserId());
			args.getGroup().setOperatorLogicPool(fxOperaIndex.getLogicalPoolId());
//			args.getGroup().setGroupLogicPool(groupPoolId);

			FXCatalogIndex fxInviteeIndex = fxUserIndexService.getFXCatalogIndex(args.getInviteeMobileNo());
			args.setInviteeUid(fxInviteeIndex.getUserId());
			args.setInviteeLogicPool(fxInviteeIndex.getLogicalPoolId());
			String rpcMethodName = null;
			if (args.getGroup().getOperateType() == (OperateType.InviteMemberJoinGroup.intValue())) {
				rpcMethodName = rpcMethodNameInvite;
			} else if (args.getGroup().getOperateType() == (OperateType.AcceptGroupInvite.intValue())) {
				rpcMethodName = rpcMethodNameAccept;
			} else {
				LOGGER.warn("OperateType No Support entity =" + args.toString());
				return;
			}

			RpcMethodStub stub = rpcClient.getMethodStub(rpcMethodName);
			RpcFuture future = stub.invoke(args);
			final String finalRpcMethodName = rpcMethodName;
			future.addListener(result ->
							LOGGER.info(String.format("invoke Fetion RPC Method:%s,retCode=%s,Args=%s", finalRpcMethodName, result.getValue().getReturnCode(), args.toString()))
			);
		} catch (Exception e) {
			LOGGER.error(String.format("process  error,Args=%s", args.toString()), e);
		}
	}


}
